<template>
	<view>
		<!-- 选择收货地址 -->
		<view class="container">
			<!-- 地址选择区域 -->
			<view class="address-item" @tap.stop="goToChooseAddress">
				<view class="address-info">
					<text class="address-name">{{ address.address }}</text>
					<text class="address-phone">{{ address.username }} {{ address.phone }}</text>
				</view>
				<view class="address-edit" @tap.stop="goToChooseAddress">
					<uni-icons type="right" size="16"></uni-icons>
				</view>
			</view>

			<view class="delivery-info">
				<view class="delivery-time">
					<text style="margin-right: 200rpx;">送达时间</text>
					<text style="font-weight: bold;">{{ deliveryTime }}</text>
				</view>
				<view class="delivery-compensation">
					<uni-tag :size="'small'" :text="'超时补偿'" type="error" inverted></uni-tag>
					<text style="margin-left: 20rpx; margin-right: 10rpx;">超时10分钟获赔300积分</text>
					<uni-icons type="help" size="16" color="#999"></uni-icons>
				</view>
				<view class="goods-list">
					<image :src="goods.image" mode="aspectFill" v-for="(goods, index) in goodsList" :key="index">
					</image>
					<view style="display: flex; align-items: center; position: absolute; right: 20rpx;">
						<text style="font-size: 28rpx; margin-right: 20rpx;">共{{ goodsList.length }}件商品</text>
					</view>
				</view>
			</view>

			<view class="payment-method">
				<view class="payment-title">
					<text>支付方式</text>
				</view>
				<view class="payment-options">
					<radio-group @change="radioChange">
						<label class="payment-option" v-for="paymentMethod in paymentMethods" :key="paymentMethod.value"
							@click.stop="selectPaymentMethod(paymentMethod.value)">
							<view style="display: flex; align-items: center;">
								<image :src="`/static/${paymentMethod.icons}.png`" mode="aspectFill"
									style="width: 40rpx; height: 40rpx;"></image>
								<text style="margin-left: 10rpx;">{{paymentMethod.name}}</text>
							</view>
							<radio :value="paymentMethod.value.toString()" :checked="paymentMethod.value === currentPaymentMethod" />
						</label>
					</radio-group>
				</view>
			</view>

			<view class="order-summary">
				<text class="total-price">实付：￥{{ totalPrice }}</text>
				<button class="submit-button" @click="submitOrder">提交订单</button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		request
	} from '@/utils/request.js';
	import {
		debounce
	} from '@/utils/common'; // 从公共工具引入
	export default {
		data() {
			return {
				orderId: '',
				deliveryTime: '尽快送达',
				goodsList: [],
				totalPrice: 0.00,
				addressId: null,
				address: {
					addressId: Number,
					username: String,
					phone: String,
					address: String,
					isDefault: Boolean
				},
				paymentMethods: [{
						name: '微信支付',
						value: 1,
						icons: 'wechat'
					},
					{
						name: '支付宝支付',
						value: 2,
						icons: 'alipay'
					},
					{
						name: '花呗支付',
						value: 3,
						icons: 'huabei'
					},
					{
						name: '银行卡支付',
						value: 4,
						icons: 'bank'
					}
				],
				currentPaymentMethod: 1, // 默认支付方式
				fromAddressSelection: false //标记是否来自地址选择页面
			}
		},
		methods: {
			// 提交订单的方法
			submitOrder: debounce(async function() {
				console.log("submitOrder:totalPrice=" + this.totalPrice);
				console.log("submitOrder:paymentMethods=" + this.paymentMethods);
				console.log("submitOrder:this.addressId=" + this.addressId);
				console.log("submitOrder:currentPaymentMethod=" + this.currentPaymentMethod);
				// 参数校验
				if (!this.addressId) {
					uni.showToast({
						title: '请选择收货地址',
						icon: 'none'
					});
					return;
				}
				if (!this.currentPaymentMethod) {
					uni.showToast({
						title: '请选择支付方式',
						icon: 'none'
					});
					return;
				}
				try {
					const resp = await request({
						url: 'order/submitOrder',
						method: 'POST',
						data: {
							addressId: this.addressId,
							paymentMethod: this.currentPaymentMethod,
							deliveryTime: this.deliveryTime
						}
					});
					this.orderId = resp.data;
					uni.navigateTo({
						url: '/pages/shoppingcart/payment?totalPrice=' + this.totalPrice +
							'&paymentMethod=' + this.paymentMethods[this.currentPaymentMethod - 1]
							.name +
							'&orderId=' + this.orderId
					});
				} catch (error) {
					console.error('提交订单失败:', error);
					uni.showToast({
						title: '订单提交失败',
						icon: 'none'
					});
				}
			}, 500),
			// 选择支付方式的方法
			radioChange(e) {
				this.currentPaymentMethod = parseInt(e.detail.value); // 转换为数字类型
				console.log("radioChange:" + this.currentPaymentMethod);
			},
			selectPaymentMethod(value) {
				this.currentPaymentMethod = value;
				console.log("selectPaymentMethod:" + this.currentPaymentMethod)
			},
			async queryDefaultAddress() {
				try {
					const resp = await request({
						url: 'shoppingCart/queryDefaultAddress',
						method: 'GET'
					});
					if (resp && resp.data) {
						this.addressId = resp.data.addressId;
						this.address = resp.data;
					}
				} catch (error) {
					console.error('获取默认地址失败:', error);
				}
			},

			// 跳转到选择地址页面
			goToChooseAddress() {
				this.fromAddressSelection = true;
				uni.navigateTo({
					url: '/pages/chooseAddress/chooseAddress'
				});
			}
		},
		onLoad(option) {
			// 优先读取 URL 参数
			if (option) {
				this.totalPrice = option.totalPrice || 0;
				this.goodsList = JSON.parse(option.products || '[]').slice(0, 4);
				this.orderId = option.orderId || '';
				// 保存到本地存储（防止页面刷新）
				uni.setStorageSync('confirmOrderParams', {
					totalPrice: this.totalPrice,
					products: option.products,
					orderId: this.orderId
				});
			} else {
				// 无 URL 参数时从本地存储读取
				const savedParams = uni.getStorageSync('confirmOrderParams');
				if (savedParams) {
					this.totalPrice = savedParams.totalPrice;
					this.goodsList = JSON.parse(savedParams.products).slice(0, 4);
					this.orderId = savedParams.orderId;
				}
			}

			// 地址初始化逻辑
			if (option?.addressId) {
				this.address = {
					addressId: option.addressId,
					username: decodeURIComponent(option.username),
					phone: option.phone,
					address: decodeURIComponent(option.address)
				};
				this.addressId = option.addressId;
			} else {
				this.queryDefaultAddress();
			}

			// 获取传递的参数
			if (option) {
				this.totalPrice = option.totalPrice;
				let list = JSON.parse(option.products);
				if (list.length > 4) {
					// 只显示前4个商品图片
					this.goodsList = list.slice(0, 4);
				} else {
					this.goodsList = list;
				}
				if (option.orderId) {
					this.orderId = option.orderId;
				}
			}
		},
		// async onShow() {
		// 	console.log(this.addressId);
		// 	if (!this.addressId) {
		// 		await this.queryDefaultAddress();
		// 	}
		// },
		onHide() {},
		onUnload() {}
	}
</script>

<style lang="scss" scoped>
	.container {
		padding: 20rpx 0;
		background-color: #f0f0f0;
		height: 100vh;
	}

	.address-item {
		background-color: #fff;
		padding: 20rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.address-info {
		display: flex;
		flex-direction: column;
	}

	.address-name,
	.address-phone {
		font-size: 24rpx;
		margin: 10rpx 0;
	}

	.address-edit {
		display: flex;
		align-items: center;
	}

	.edit-text {
		margin-right: 10rpx;
	}

	.address-edit uni-icons {
		color: #999;
	}

	.delivery-info {
		background-color: #fff;
		padding: 20rpx 0;
		margin-bottom: 20rpx;
	}

	.delivery-time {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx;
		font-size: 28rpx;
	}

	.delivery-compensation {
		display: flex;
		align-items: center;
		padding-left: 20rpx;
		padding-bottom: 20rpx;
		margin-bottom: 20rpx;
		font-size: 24rpx;
		border-bottom: 1px solid #f0f0f0;
	}

	.goods-list {
		display: flex;
		align-items: center;
		margin-top: 20rpx;

		image {
			width: 100rpx;
			height: 100rpx;
			border-radius: 50%;
			border: 1px solid #f0f0f0;
			margin: 0 10rpx;
		}
	}

	.payment-method {
		background-color: #fff;
		padding: 20rpx 0;
		margin-bottom: 20rpx;
	}

	.payment-title {
		font-size: 28rpx;
		margin-bottom: 20rpx;
		border-bottom: 1px solid #f0f0f0;
		padding-bottom: 20rpx;
		padding-left: 20rpx;
	}

	.payment-options {
		display: flex;
		flex-direction: column;
	}

	.payment-option {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx;
	}

	.payment-option text {
		font-size: 28rpx;
	}

	.order-summary {
		background-color: #fff;
		padding: 20rpx;
		position: fixed;
		bottom: 20rpx;
		width: 100%;
		display: flex;
		align-items: center;
	}

	.total-price {
		font-size: 32rpx;
		color: #333;
	}

	.submit-button {
		background-color: #007AFF;
		color: #fff;
		padding: 20rpx 40rpx;
		border-radius: 100rpx;
		font-size: 28rpx;
		border: none;
		margin-left: 320rpx;
	}
</style>